<template>
    <div class="box2">
        <div class="friends">
            <div class="search" v-if="flag == 2">
                <el-input ref="inputBox" placeholder="添加朋友" class="input" v-model="keyword" :prefix-icon="Search"
                    @change="searchUser()">
                </el-input>
                <div class="cancel" @click="cancel()">取消</div>
            </div>
            <div class="search" v-else>
                <el-input ref="inputBox" placeholder="搜索朋友" class="input" v-model="keyword" :prefix-icon="Search"
                    clearable @focus="handleFocus" @blur="handleBlur" @clear="handleClear" @change="searchfriend()">
                </el-input>
                <el-tooltip class="box-item" effect="dark" content="添加朋友" placement="bottom-end">
                    <el-button class="btn" :icon="Plus" size="small" @click="addnewfriends()" />
                </el-tooltip>

            </div>
            <!-- 遍历 newsData 数据 -->
            <el-scrollbar v-if="flag == 0">
                <!-- 新的朋友 -->
                <div class="newFriends" @click="getNewfriends" :class="{ newselected }">
                    <div class="pic">
                        <img src="../assets/OIP-C (1).jpg" alt="头像" />
                    </div>
                    <!-- 名字 -->
                    <div class="name" :class="{ newselected }">新的朋友</div>
                </div>
                <div class="friend" v-for="(item, index) in userStore.friendsList" :key="index" @click="getfiendInfo(item)"
                    :class="{ selected: item.selected }">
                    <!-- 头像 -->
                    <div class="pic">
                        <img :src="item.avatar" alt="头像" />
                    </div>
                    <!-- 名字 -->
                    <div class="name">{{ item.username }}</div>
                </div>
            </el-scrollbar>
            <el-scrollbar v-else-if="flag == 1">
                <div class="friend" v-for="(item, index) in search_friensData" :key="index" @click="getfiendInfo(item)">
                    <!-- 头像 -->
                    <div class="pic">
                        <img :src="item.avatar" alt="头像" />
                    </div>
                    <!-- 名字 -->
                    <div class="name">{{ item.username }}</div>
                </div>
            </el-scrollbar>
            <el-scrollbar v-else-if="flag == 2">
                <div class="addfriend" v-for="(item, index) in search_newfriensData" :key="index"
                    @click="isfriend(item)">
                    <!-- 头像 -->
                    <div class="info">
                        <div class="pic">
                            <img :src="item.avatar" alt="头像" />
                        </div>
                        <!-- 名字 -->
                        <div class="name">{{ item.username }}</div>
                    </div>
                    <div class="btn" v-if="item.isFriend == false"><el-button color="#626aef" size="small"
                            @click="addfriend(item)">添加</el-button>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div class="friendinfo">
            <router-view v-if="hasContent"></router-view>
            <div v-else class="no-content">
                <el-empty description="请选择好友" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue';
import { reqAddfriend, reqAllUser, reqUserInfo } from '@/api/user';
import type { ReqfriendsData, friendsData } from '../types/type'
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
//引入用户相关的仓库,获取当前用户的头像、昵称
import useUserStore from '@/store/modules/user';
import { ElMessage } from 'element-plus';

//获取存储用户信息的仓库对象
let userStore = useUserStore();
const router = useRouter()
const route = useRoute()
let flag = ref(0);
// 获取输入框的引用
const inputBox = ref<any>();
// 所有好友数组
let friendsData = reactive<friendsData>([]);
// 好友申请信息
const newselected = ref(false)
// 查询好友得到的数值
let search_friensData = ref<friendsData>([]);
// 查询非好友得到的数值
let search_newfriensData = ref<friendsData>([]);
// 输入框内容
let keyword = ref('')
const hasContent = ref(false); // 用于判断 router-view 是否有内容
const userId = userStore.userId;
// 搜索框得到焦点
const handleFocus = () => {
    if (flag.value == 0) {
        flag.value = 1;
    }
    search_friensData.value = []
}
// 搜索好友
const searchfriend = async () => {
    // 查询好友列表

    const result: ReqfriendsData = await reqUserInfo({ userId, keyword: keyword.value });
    if (result.code == 200) {
        // 不直接赋值，而是通过数组操作保持响应式
        search_friensData.value.splice(0, search_friensData.value.length, ...result.data);

    }
}
// 输入框失去焦点时隐藏清除按钮
const handleBlur = () => {
    if (keyword.value == '') {
        flag.value = 0;
        search_friensData.value = []
    } else {
        // 查询好友列表
        searchfriend()
    }
};
// 清除按钮
const handleClear = () => {
    // 清空查询结果,删除 search_friensData
    search_friensData.value = []
    flag.value = 0;
    // 手动改变输入框的焦点状态
    inputBox.value?.blur();
}
const getfiendInfo = (friend: any) => {
    console.log(friend);
    hasContent.value = true
    // flag.value = 0;
    let Id = friend._id
    updateSelection(friend._id)
    router.push({ name: 'frienRoom', params: { id: Id ,roomName:friend.roomName} });
   

}
onMounted(() => {
    const fid = route.params.id;
    const meta = route.meta;
    console.log(meta);


    if (fid) {
        hasContent.value = true;

    }
    else if (meta.activeTab == 'newfriend') {
        hasContent.value = true;
        newselected.value = true
    }
    else {
        hasContent.value = false;
    }
    getinfo()

})

const getinfo = async () => {


        flag.value = 0;
        const fid = route.params.id;
        if (fid) {
            updateSelection(fid)
        }
    
}
const updateSelection = (friendId: any) => {

    userStore.friendsList.forEach((item:any) => {
        if (item._id === friendId) {
            item.selected = true;
            newselected.value = false;
        } else {
            item.selected = false;
        }
    });
};
// 新朋友申请信息界面
const getNewfriends = () => {
    router.push('/newfriends');
    updateSelection(0);
    newselected.value = true;
    hasContent.value = true;
}
// 添加新好友界面
const addnewfriends = () => {
    flag.value = 2;

}
// 取消
const cancel = () => {
    flag.value = 0;
    search_newfriensData.value = [];
    keyword.value = ''
}
// 查询用户
const searchUser = async () => {
    const result = await reqAllUser({ userId, friendname: keyword.value })
    if (result.code == 200) {
        search_newfriensData.value.splice(0, search_newfriensData.value.length, ...result.data)
    }
    // 与friendsData数组进行比较，相同的添加一个状态是好友，不同则是陌生人
    search_newfriensData.value.forEach((user) => {
        // 判断该用户是否在 friendsData 中
        const isFriend = friendsData.some(friend => friend._id === user._id);
        // 添加 isFriend 属性
        user.isFriend = isFriend;
    });
}
// 添加朋友
const addfriend = async (friend: any) => {
    const result = await reqAddfriend({ userId, friendId: friend._id });
    console.log(result);

    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: result.message
        })
    }
}
const isfriend = (friend: any) => {
    if (friend.isFriend) {
        hasContent.value = true
        let Id = friend._id
        router.push({ name: 'frienRoom', params: { id: Id } });
    }
}
</script>

<style scoped lang="scss">
.box2 {
    display: flex;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .friends {
        width: 350px;
        height: 100vh;
        background: #f1f1f1;
        border-right: 1.5px solid #E0E0E0;

        .search {
            position: sticky;
            /* 固定在顶部 */
            top: 0;
            z-index: 10;
            /* 确保搜索框在最上层 */
            width: 100%;
            height: 70px;
            padding: 15px;
            background-color: #f1f1f1;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

            /* 可选，增加阴影效果 */
            .input {
                width: 90%;
                height: 30px;

            }

            .cancel {
                width: 30px;
                height: 30px;
                line-height: 30px;
                margin-left: 10px;
                font-size: 12px;
                color: #000;
                cursor: pointer;
            }

            .btn {
                margin-left: 10px;
                width: 30px;
                height: 30px;

                &:hover {
                    background-color: #E0E0E0;
                    color: #333;
                }
            }
        }

        .newFriends {
            height: 75px;
            width: 100%;
            overflow-y: auto;
            /* 使 news 容器能够滚动 */
            display: flex;
            align-items: center;
            background-color: #f1f1f1;
            padding: 15px;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */

            &:hover {
                background-color: #E0E0E0;
                /* 鼠标悬停时的背景颜色 */
            }

            &.newselected {
                /* 当某一条消息被选中时 */
                background-color: #d0d0d0;
                /* 更深的背景色 */
                box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                /* 选中时的阴影效果 */
            }

            .pic {
                width: 40px;
                height: 40px;
                // border-radius: 50%;
                overflow: hidden;
                margin-right: 10px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

            }

            .name {
                font-size: 16px;
                font-weight: 500;
                color: #333;
            }
        }

        .friend {
            height: 75px;
            width: 100%;
            overflow-y: auto;
            /* 使 news 容器能够滚动 */
            display: flex;
            align-items: center;
            background-color: #f1f1f1;
            padding: 15px;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */

            &:hover {
                background-color: #E0E0E0;
                /* 鼠标悬停时的背景颜色 */
            }

            &.selected {
                /* 当某一条消息被选中时 */
                background-color: #d0d0d0;
                /* 更深的背景色 */
                box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                /* 选中时的阴影效果 */
            }

            .pic {
                width: 40px;
                height: 40px;
                // border-radius: 50%;
                overflow: hidden;
                margin-right: 10px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

            }

            .name {
                font-size: 16px;
                font-weight: 500;
                color: #333;
            }
        }

        .addfriend {
            height: 75px;
            width: 100%;
            overflow-y: auto;
            /* 使 news 容器能够滚动 */
            display: flex;
            align-items: center;
            background-color: #f1f1f1;
            padding: 15px;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */
            justify-content: space-between;

            &:hover {
                background-color: #E0E0E0;
                /* 鼠标悬停时的背景颜色 */
            }

            &.selected {
                /* 当某一条消息被选中时 */
                background-color: #d0d0d0;
                /* 更深的背景色 */
                box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                /* 选中时的阴影效果 */
            }

            .info {
                display: flex;

                .pic {
                    width: 40px;
                    height: 40px;
                    // border-radius: 50%;
                    overflow: hidden;
                    margin-right: 10px;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }

                }

                .name {
                    font-size: 16px;
                    font-weight: 500;
                    color: #333;
                    line-height: 40px;
                }
            }

            .btn {
                margin-right: 20px;
            }
        }

    }


    .friendinfo {

        width: 75%;
        height: 100vh;

        .no-content {
            width: 100%;
            height: 100%;
            text-align: center;
            padding: 200px;
        }

    }
}
</style>